import http from '@/axios'
import { handleSuccess, handleError } from '@/utils/responseHandler'

/**
 * 日志管理相关API
 */
export const LogApi = {
    /**
     * 获取日志列表（分页）
     * @param {Object} params - 查询参数
     * @returns {Promise} 日志列表Promise
     */
    getLogList: (params) =>
        http.get('/log/list', { params })
            .then(res => handleSuccess(res, '获取日志列表成功'))
            .catch(error => handleError(error, '获取日志列表失败')),

    /**
     * 获取日志详情
     * @param {Number} id - 日志ID
     * @returns {Promise} 日志详情Promise
     */
    getLogDetail: (id) =>
        http.get(`/log/detail/${id}`)
            .then(res => handleSuccess(res, '获取日志详情成功'))
            .catch(error => handleError(error, '获取日志详情失败')),

    /**
     * 获取日志统计数据
     * @param {Object} params - 统计参数
     * @returns {Promise} 统计数据Promise
     */
    getLogStatistics: (params) =>
        http.get('/log/statistics', { params })
            .then(res => handleSuccess(res, '获取日志统计成功'))
            .catch(error => handleError(error, '获取日志统计失败')),

    /**
     * 导出日志为CSV
     * @param {Object} params - 导出参数
     * @returns {Promise} 导出Promise
     */
    exportLogs: (params) => {
        // 过滤空值参数
        const filteredParams = {};
        Object.keys(params).forEach(key => {
            if (params[key] !== null && params[key] !== undefined && params[key] !== '') {
                filteredParams[key] = params[key];
            }
        });

        return http({
            method: 'get',
            url: '/log/export',
            params: filteredParams,
            responseType: 'blob'
        }).then(response => {
            // 直接处理文件下载
            const blob = new Blob([response.data], { type: 'text/csv;charset=utf-8' });
            const url = window.URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;

            // 从响应头中提取文件名
            const contentDisposition = response.headers['content-disposition'];
            let fileName = '操作日志.csv';
            if (contentDisposition) {
                const match = contentDisposition.match(/filename\*?=UTF-8''(.+)/i);
                if (match && match[1]) {
                    fileName = decodeURIComponent(match[1]);
                }
            }

            link.setAttribute('download', fileName);
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            window.URL.revokeObjectURL(url);

            return response;
        }).catch(error => {
            console.error('导出失败:', error);

            // 简化且安全的错误处理
            let errorMsg = '导出日志失败，请稍后重试';
            if (error) {
                if (error.message && !error.message.includes('undefined')) {
                    errorMsg = error.message;
                } else if (error.response && error.response.status) {
                    errorMsg = `导出失败，HTTP状态码: ${error.response.status}`;
                }
            }
            throw new Error(errorMsg);
        });
    }

}